var layer,
    form,
    table,
    $;
var user = {userId : '1002'};
var user = JSON.parse(localStorage.getItem('user'));
layui.use(['jquery', 'layer', 'form', 'table'], function () {
    layer = layui.layer,
        table = layui.table,
        form = layui.form,
        $ = layui.jquery;


    //修改状态
    form.on('switch(swi)', function(data){
        if (data.elem.checked){
            updateproductSate(data.elem.value,1);
        }else{
            updateproductSate(data.elem.value,2);
        }
    });

});

getZtree();
function getZtree() {

    //zTree的参数设置
    var zTreeObj

    //zTree的数据属性
    var setting = {
        view:{
            showIcon:false,
            selectedMulti:false,
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "categroyId",  //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",  //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            key: {
                name: "title",  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        callback: {
            onClick: onClick,//鼠标点击到节点时回调
            onRightClick: onRightClick//鼠标右击时回调
        },
        check: {
            enable: true,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
            chkStyle: "checkbox", //checkbox 选择框、 radio 选择框，setting.check.chkboxType 属性有效。
            nocheckInherit: true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        }
    };

    function onClick(event, treeId, treeNode) {
        getTableData(treeNode.categroyId)
    };

    function onRightClick (event, treeId, treeNode) {
        node = treeNode;
        if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
            var zTree = $.fn.zTree.getZtreeObj(treeId);
            zTree.cancelSelectedNode();
            showRMenu("root", event.clientX, event.clientY);
        } else if (treeNode && !treeNode.noR) {
            categroyId = treeNode.categroyId;
            showRMenu(event.target,"node", event.clientX, event.clientY);
        }
    }
    //显示右键菜单
    function showRMenu(event,type, x, y) {
        $("#rMenu").show();
        $("#rMenu").css({"top": y + "px", "left": x + "px", "visibility": "visible"}); //设置右键菜单的位置、可见
        $("body").bind("mousedown", onBodyMouseDown);
    }

    //隐藏右键菜单
    function hideRMenu() {
        $("#rMenu").css({"visibility": "hidden"}); //设置右键菜单不可见
        $("body").unbind("mousedown", onBodyMouseDown);
    }
    //鼠标按下事件
    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            // $("#rMenu").hide();
            $("#rMenu").css({ "visibility": "hidden"});
        }
        hideRMenu();
    }

    var zNodes;
    layui.use([ 'form'], function () {
        form = layui.form;
        $.ajax({
            url:'/Product/getAllProductCategroy',
            async: false,
            dataType: 'json',
            success: function (item) {
                zNodes = item.data;
                item.data.forEach(function(ele, index){
                    $('#proTitle').append(new Option(ele.title, ele.categroyId));// 下拉菜单里添加元素
                });
                form.render("select");
            }
        });
    })


    $(document).ready(function () {
        zTreeObj = $.fn.zTree.init($('#treeDemo'), setting, zNodes);
        zTreeObj.expandAll(true);    //true 节点全部展开、false节点收缩
    });
};

//删除分类
function delnode() {
    if(node.categroyId === 1){
        layer.msg("该目录不可删除");
        return;
    }
    if(confirm("确认删除"+node.title+"商品类?")){
        if(node.isParent){
            layer.msg("该目录下面还有子目录，请从最底层目录开始删除!");
            return false;
        }
        $.ajax({
            url:'/Product/deleteProductCategroy',
            data:{"categoryId":node.categroyId},
            dataType:'json',
            success:function (data) {
                if(data.data){
                    layer.msg("删除成功");
                    getZtree();
                    $("#rMenu").css({"visibility": "hidden"}); //设置右键菜单不可见
                    $("body").unbind("mousedown", onBodyMouseDown);
                    return true;
                }else{
                    layer.msg("删除失败");
                    return false;
                }
            }
        });
    }
};


//添加分类
function addHoverDom(){
    layer.prompt({
        formType: 2,
        title: '添加分类',
        area: ['500px', '30px'] //自定义文本域宽高
    }, function(value, index, elem){
        if (value.length < 7){
            $.ajax({
                url:'/Product/addProductCategroy',
                dataType:'json',
                data:{
                    "parentId": node.categroyId,
                    "sort": null,
                    "title": value,
                    "createDate": getDate(),
                    "categroy":1,
                    "createId": user.userId
                },
                success:function (data) {
                    if(data.data){
                        layer.msg("添加成功");
                        getZtree();
                    }else{
                        layer.msg("添加失败");
                    }
                }
            });
            layer.close(index);
        } else {
            layer.msg("分类名字长度最大为：6");
        }
    });
}
//修改分类
function Rename() {
    layer.prompt({
        formType: 2,
        title: '修改分类名',
        area: ['500px', '30px'] //自定义文本域宽高
    }, function(value, index, elem){
        if(value.length < 3){
            alert("名称不能少于3个字符！");
        }else{
            $.ajax({
                url:'/Product/updateProductCategroy',
                data:{
                    "categroyId":node.categroyId,
                    "title":value,
                    "updateId": user.userId,
                    "updateDate":getDate(),
                },
                dataType:'json',
                success:function (data) {
                    if(data.data){
                        layer.msg("修改成功");
                        getZtree();
                        getTable();
                        return true;
                    }else{
                        layer.msg("修改失败");
                        return false;
                    }
                }
            });
            layer.close(index);
        }
    });
};


//表数据
getTableData();
function getTableData(categroyId, productId, productName, productLabel, productSate, productCode, currentpriceProduct){
    $.ajax({
        url:'/Product/getProduct',
        type: 'post',
        dataType: 'json',
        data: {
            'categroyId' : categroyId,
            'productId' : productId,
            'productName' : productName,
            'productLabel' : productLabel,
            'productSate' : productSate,
            'productCode' : productCode,
            'currentpriceProduct' : currentpriceProduct,
            'type' : 3
        },
        success: function (item) {
            getTable(item.data);
        }
    });
}

//查询表
function getTable(data) {
    layui.use(['jquery', 'layer', 'table'], function () {
        table = layui.table;

        table.render({
            elem: '#demo',
            data: data,
            toolbar:'#toolutil',
            page:true,
            limit:10,
            text: {
                none: '暂无相关数据' //默认：无数据。
            },
            cols:[[
                {checkbox:true},
                {field:'productCode',title:'商品编号',align:'center',height:'20px'},
                {title:'商品图片',align:'center',templet:function(data){
                        return "<img src='"+data.mainImage+"'width='80px' height='80px'/>";
                    }},
                {field:'productName',title:'商品名称',align:'center'},
                {field:'currentpriceProduct',title:'商品价格',align:'center'},
                {title:'上架/下架',align:'center',templet:function(data){
                        if(data.productSate === 1){
                            return"<input type='checkbox' value='"+data.productId+"' lay-filter='swi' lay-skin='switch' lay-text='上架|下架' checked>";
                        }else if(data.productSate === 0){
                            return "<span>已删除</span>";
                        }else{
                            return"<input type='checkbox' value='"+data.productId+"' lay-filter='swi' lay-skin='switch' lay-text='上架|下架'>";
                        }
                    }},
                {field:'title',title:'商品分类',align:'center'},
                {field:'productLabel',title:'商品标签',align:'center'},
                {field:'result',title:'审核状态',align:'center',templet:function(data){
                        var result;
                        if(data.result == 1){
                            result = "审核通过";
                        }else if(data.result == 2){
                            result = "待审核";
                        }else if(data.result == 3){
                            result = "审核驳回";
                        }else{
                            result = "";
                        }
                        return "<div>"+result+"</div>" +
                            "<a class='operation' onclick='auditDetails("+data.productId+")'>审核详情</a>";
                }},
                {field:'title',title:'操作',align:'center',templet:function(data){
                        return "<a class='operation' onclick='details("+data.productId+")'>查看</a>  <a class='operation' onclick='edit("+data.productId+")'>编辑</a> <br/>"+
                            "<a class='operation' onclick='commodityLog("+data.productId+")'>日志</a>  <a onclick='delProduct(\""+data.productId+"\",\""+data.productCode+"\")' class='operation'>删除</a>";
                }},
            ]]
        });
    });

};

//修改商品状态
function updateproductSate(productId, productSate) {
    $.ajax({
        url:'/Product/updateProduct',
        dataType: 'json',
        data: {
            'productId': productId,
            'productSate': productSate,
            "updateId": user.userId,
            "updateDate":getDate(),
        },
        success: function (item) {
            if (item.data){
                if (productSate == 1){
                    layer.msg("上架成功");
                }else if (productSate == 2){
                    layer.msg("下架成功");
                }
            }else{
                layer.msg("操作失败");
            }
        }
    });
};

//查看审核信息
function auditDetails (id) {
    layer.open({
        type:2,
        offset: 'auto',
        title: '审核详情',
        resize: false,
        area:['1020px','500px'],
        content:'/product/productList-layer/product-auditDetails.html?tx=' + encodeURI(id)
    });
};

//查看商品详情信息
function details (id) {
    layer.open({
        type: 2,
        offset: 'auto',
        title: '商品详情',
        resieze: false,
        area: ['1100px', '500px'],
        content: '/product/productList-layer/productDetails.html?tx=' + encodeURI(id)
    });
};

//删除商品
function delProduct  (id) {
    layer.open({
        type: 1,
        offset: 'auto',
        resize: false,
        area:['300px','200px'],
        btn:["确定","取消"],
        content:"<div style='font-size: 20px ; color: red; margin:30px  ;'>是否删除此商品?</div>",
        yes: function (index, layero) {
            $.ajax({
                url: '/Product/deleteProduct',
                dataType: 'json',
                data: {
                    'id': id
                },
                success: function (item) {
                    if (item.data) {
                        layer.msg("删除成功");
                        addProductOperationRecord(4, getDate(), "删除商品信息");
                        getTableData();
                        layer.close(index);
                    } else {
                        layer.msg("删除失败");
                    }
                }
            });
        },
        btn2: function (index, layero) {
            layer.close(index);
        }
    });
}

function addProductOperationRecord(operationType, executionTime, remarks) {
    // 添加的操作日志
    $.ajax({
        url:'/Product/addProductOperationRecord',
        dataType:'json',
        data:{
            "operationType": operationType,
            "executionTime": executionTime,
            "remarks": remarks,
            "updateId": user.userId,
            "operationList": 'js_product',
            "type": 1
        }
    });
};

//修改商品信息
function edit(id) {
    layer.open({
        type: 2,
        offset: 'auto',
        title: '商品详情',
        resieze: false,
        area: ['680px', '550px'],
        content:'/product/productList-layer/productlist-modify.html?tx=' +　encodeURI(id)
    });
};

//查看商品的操作日志
function commodityLog () {
    layer.open({
        type: 2,
        offset: 'auto',
        title: '商品日志详情',
        resize: false,
        maxmin: true,
        area: ['1480px', '800px'],
        content:'/product/productJournal.html'
    })
};

//添加商品
function addProduct (){
    parent.jump("添加商品");
}

//搜索
function selProduct () {
    var data = form.val("formTest");
    getTableData(data.categroyId, null, data.title, data.productLabel, data.productSate)
}

//高级检索
function accurate () {
    layer.open({
        type: 2,
        offset: 'auto',
        title: '信息',
        resize: false,
        area: ['600px', '500px'],
        content: '/product/productList-layer/productlist-precisesearch.html'
    });
}

//获取时间
function getDate() {
    var date = new Date().toLocaleString('zh', { hour12: false }).split('/').join('-');
    var temp = date.substring(0, 9);
    date = date.substr(date.lastIndexOf('-') + 3);
    date = temp + date;
    return date;
}

//刷新页面
function refresh (){
    location.reload();
}

//返回首页
function backOff(){
    parent.jumpSystemHome();
}